package com.gitee.dufafei.plugin.vfs.config;

import com.gitee.dufafei.plugin.vfs.FileVFS;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.DelegatingFileSystemOptionsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class GenericFileSystemConfigBuilder extends FileSystemConfigBuilder implements FileSystemConfigInterface {

    private static Logger logger = LoggerFactory.getLogger(GenericFileSystemConfigBuilder.class);

    @Override
    protected Class<? extends FileSystem> getConfigClass() { return FileSystem.class;}

    @Override
    public String parseParameterName(String parameter) {
        String result;
        // Whether the parameter contains '.'
        int end = parameter.indexOf(".");
        if(end < 0) {
            // do not contain
            result = parameter;
        } else {
            result = parameter.substring(0, end);
        }
        return result;
    }

    @Override
    public void setParameter(FileSystemOptions opts, String scheme, String key, String value) throws IOException {
        try {
            DelegatingFileSystemOptionsBuilder delegateFSOptionsBuilder = new DelegatingFileSystemOptionsBuilder(FileVFS.getFileSystemManager());
            delegateFSOptionsBuilder.setConfigString(opts, scheme, key, value);
        } catch (FileSystemException e) {
            if (e.getCode().equalsIgnoreCase( "vfs.provider/config-key-invalid.error")) {
                // This key is not supported by the default scheme config builder.
                // This may be a custom key of another config builder
                logger.warn("Warning: The configuration parameter [" + key + "] " +
                        "is not supported by the default configuration builder for scheme: " + scheme);
            } else {
                // An unexpected error has occurred loading in parameters
                throw new IOException(e.getLocalizedMessage());
            }
        }
    }
}
